package com.insmess.speech.controller;

import com.insmess.speech.common.api.CommonResult;
import com.insmess.speech.dto.AsrDto;
import com.insmess.speech.dto.TtsParamDto;
import com.insmess.speech.sdk.template.InsmessAsrTemplate;
import com.insmess.speech.service.AsrService;
import com.insmess.speech.service.TtsService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

@Slf4j
@RestController
@RequestMapping("/tts")
public class TtsController {
    @Autowired
    private TtsService ttsService;

    @SneakyThrows
    @PostMapping("/getFileBase64")
    public CommonResult getFileBase64(@RequestBody TtsParamDto ttsParamDto) {
        String base64 = ttsService.ttsBase64(ttsParamDto);
        return CommonResult.success(base64);
    }

    @SneakyThrows
    @PostMapping("/getFile")
    public void getFile(@RequestBody TtsParamDto ttsParamDto, HttpServletResponse response) {
        File sourceFile = ttsService.tts(ttsParamDto);
        InputStream in = new FileInputStream(sourceFile);
        ServletOutputStream out = response.getOutputStream();
        response.setHeader("Content-Disposition", "attachment;filename=" + sourceFile.getName());
        IOUtils.copy(in, out);
        out.close();
        in.close();
    }
}
